package cn.clementine.core.utils;

import java.io.*;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

public class FileUtil {
    public static String readFileContent(String filePath) throws IOException {
        StringBuilder content = new StringBuilder();
        BufferedReader reader = null;
        try {
            File file = new File(filePath);
            FileInputStream fis = new FileInputStream(file);
            Charset encoding = detectEncoding(filePath);
            InputStreamReader isr = new InputStreamReader(fis, encoding);
            reader = new BufferedReader(isr);
            String line;
            while ((line = reader.readLine()) != null) {
                content.append(line);
                content.append(System.lineSeparator());
            }
        } finally {
            if (reader != null) {
                reader.close();
            }
        }
        return content.toString();
    }
    public static boolean isFileGreaterThan10MB(String filePath) {
        File file = new File(filePath);
        long fileSizeInBytes = file.length();
        long fileSizeInMB = fileSizeInBytes / (1024 * 1024);

        return fileSizeInMB > 10;
    }
    public static Charset detectEncoding(String filePath) throws IOException {
        File file = new File(filePath);
        try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file))) {
            byte[] buffer = new byte[4096];
            int bytesRead = bis.read(buffer);
            if (bytesRead > 2 && buffer[0] == (byte) 0xFF && buffer[1] == (byte) 0xFE) {
                return StandardCharsets.UTF_16LE;
            }
            if (bytesRead > 2 && buffer[0] == (byte) 0xFE && buffer[1] == (byte) 0xFF) {
                return StandardCharsets.UTF_16BE;
            }
            if (bytesRead > 3 && buffer[0] == (byte) 0xEF && buffer[1] == (byte) 0xBB && buffer[2] == (byte) 0xBF) {
                return StandardCharsets.UTF_8;
            }
            return Charset.defaultCharset();
        }
    }
}
